package cn.jsxz.common.utils.ImageUtil;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ImageEdit
 * @Description TODO
 * @Author Admin
 * @Date 14:07
 * @Version 1.0
 **/
public class ImageEdit {

    public static void main(String[] a) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("orderNo", "2019011415890439");
        map.put("shopName", "你的海盐直营店");
        map.put("phone", "13101829291");
        map.put("address", "江苏省徐州泉山区奎东村6单元406栋5喽超出部分");
        map.put("createTime", "2019-01-17 13:44:00");
        map.put("userName", "张三");

        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map1 = new LinkedHashMap<>();
        map1.put("saltName", "天然湖盐巴无碘精致食用盐超出的部分");
        map1.put("type", "箱装");
        map1.put("num", "100000");
        Map<String, Object> map2 = new LinkedHashMap<>();
        map2.put("saltName", "大自然的纯净无碘食用盐");
        map2.put("type", "袋装");
        map2.put("num", "100000");
        Map<String, Object> map3 = new LinkedHashMap<>();
        map3.put("saltName", "大自然的纯净无碘食用盐1111");
        map3.put("type", "袋装");
        map3.put("num", "100000");
        Map<String, Object> map4 = new LinkedHashMap<>();
        map4.put("saltName", "大自然的纯净无碘食用盐2222");
        map4.put("type", "袋装");
        map4.put("num", "100000");
        mapList.add(map1);
        mapList.add(map2);
        mapList.add(map3);
        mapList.add(map4);
        map.put("text10", mapList);
        ImageEdit.createStringMark("D://top.jpg", map, "d://B.jpg");
    }


    /**
     * @param filePath 源图片路径
     * @param @params: [filePath, maps, outPath] 图片中添加内容
     * @param outPath  输出图片路径,字体颜色等在函数内部实现的
     */
    //给jpg添加文字
    public static boolean createStringMark(String filePath, Map<String, Object> maps, String outPath) {

//        ImageIcon imgIcon = new ImageIcon(filePath);//电子票据上半部分
        String topPath = filePath + "/top.jpg";
//        D://top.jpg
//        http://localhost:8080/OrderMS_Java/img/top.jpg
        //D:\git_project\OrderMS_Java\target\OrderMS_Java\img/top.jpg
        ImageIcon imgIcon = new ImageIcon(topPath);//电子票据上半部分
        Image theImg = imgIcon.getImage();
        int width = theImg.getWidth(null) == -1 ? 150 : theImg.getWidth(null);
        int height = theImg.getHeight(null) == -1 ? 150 : theImg.getHeight(null);
        System.out.println("width==========" + width);
        System.out.println("height=========" + height);

//        ImageIcon imageIcon1 = new ImageIcon("d://down.jpg");//电子票据下半部分
        String downPath = filePath + "/down.jpg";
        ImageIcon imageIcon1 = new ImageIcon(downPath);//电子票据下半部分
        Image theImg1 = imageIcon1.getImage();

//        ImageIcon imageIcon = new ImageIcon("d://YZ.jpg");//印章图
        String YZPath = filePath + "/YZ.jpg";
        ImageIcon imageIcon = new ImageIcon(YZPath);//印章图
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(220, 220, Image.SCALE_DEFAULT));
        Image theImg2 = imageIcon.getImage();

        BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bImage.createGraphics();//创建画布对象
        g.setBackground(Color.WHITE);//设置背景色
        g.clearRect(0, 0, width, height);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
        Color color = Color.DARK_GRAY;
        g.setColor(color);
        g.setBackground(Color.DARK_GRAY);
        g.drawImage(theImg, 0, 0, null);
        g.setFont(new Font("宋体", Font.PLAIN, 30));//字体、字型、字号
        int x = 0;
        int y = 0;
        for (Map.Entry<String, Object> entry : maps.entrySet()) {
            String key = entry.getKey();
            if (key.equals("orderNo")) {
                x = 160;
                y = 125;
                g.drawString(entry.getValue().toString(), x, y); //画文字
                System.out.println("单号" + x);
                System.out.println("单号" + y);
            } else if (key.equals("shopName")) {
                y = y + 60;
                g.drawString(entry.getValue().toString(), x, y); //画文字
                System.out.println("店铺名称" + x);
                System.out.println("店铺名称" + y);
            } else if (key.equals("phone")) {
                y = y + 55;
                System.out.println("电话" + x);
                System.out.println("电话" + y);
                g.drawString(entry.getValue().toString(), x, y); //画文字
            }
        }
        x = 15;
        y = y + 150;
        //明细渲染
        JSONObject json = JSONObject.fromObject(maps);
        JSONArray jsonArray = json.getJSONArray("detail");
        for (int i = 0; i < jsonArray.size(); i++) {
            String saltName = jsonArray.getJSONObject(i).getString("saltName");
            char[] chars = saltName.toCharArray();
            if (chars.length <= 13) {
                g.drawString(saltName, x, y); //画文字-盐品名称
                int type = Integer.parseInt(jsonArray.getJSONObject(i).getString("norms"));
                String saltType = "";
                if (type == 1) {
                    saltType = "袋装";
                } else {
                    saltType = "箱装";
                }
                g.drawString(saltType, x + 435, y); //画文字-规格
                g.drawString(jsonArray.getJSONObject(i).getString("num"), x + 560, y); //画文字-数量
                y = y + 50;
            } else {
                g.drawString(saltName.substring(0, 13), x, y); //画文字-盐品名称
                y = y + 30;
                g.drawString(saltName.substring(13), x, y); //画文字-盐品名称
                int type = Integer.parseInt(jsonArray.getJSONObject(i).getString("norms"));
                String saltType = "";
                if (type == 1) {
                    saltType = "袋装";
                } else {
                    saltType = "箱装";
                }
                g.drawString(saltType, x + 435, y); //画文字-规格
//                g.drawString(jsonArray.getJSONObject(i).getString("saltType"), x + 440, y - 20); //画文字-规格
                g.drawString(jsonArray.getJSONObject(i).getString("num"), x + 560, y - 20); //画文字-数量
                y = y + 50;
            }
        }
        System.out.println("明细最后高度" + y);
        y = y + 20;
        x = 160;
        System.out.println("下半部分开始高度" + y);
        g.drawImage(theImg1, 0, y, null);//添加下半部分
        for (Map.Entry<String, Object> entry : maps.entrySet()) {
            String key = entry.getKey();
            if (key.equals("address")) {
                y = y + 58;
                char[] chars = entry.getValue().toString().toCharArray();
                if (chars.length <= 20) {
                    g.drawString(entry.getValue().toString(), x, y); //画文字
                } else {
                    g.drawString(entry.getValue().toString().substring(0, 20), x, y); //画文字
                    g.drawString(entry.getValue().toString().substring(19), x, y + 30); //画文字
                }
            } else if (key.equals("createTime")) {
                y = y + 88;
                g.drawString(entry.getValue().toString(), x, y); //画文字
            } else if (key.equals("userName")) {
                y = y + 56;
                g.drawString(entry.getValue().toString(), x, y); //画文字
            }
        }
        g.drawImage(theImg2, 450, y - 198, null);//添加印章
        y = y + 28;
        g.dispose();//画布关闭
        try {
            FileOutputStream out = new FileOutputStream(outPath); //先用一个特定的输出文件名
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bImage);
            param.setQuality(1000, true);  //
            encoder.encode(bImage, param);
            out.close();
//            ImageEdit.cutImage("D://B.jpg", "D://", 0, 0, 700, y);
            String BPath = filePath + "/B.jpg";
            ImageEdit.cutImage(BPath, filePath, 0, 0, 702, y);//生成切图
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //============================切图
    private static String DEFAULT_CUT_PREVFIX = "cut_";

    /**
     * <p>Title: cutImage</p>
     * <p>Description:  根据原图与裁切size截取局部图片</p>
     *
     * @param srcImg 源图片
     * @param output 图片输出流
     * @param rect   需要截取部分的坐标和大小
     */
    public static void cutImage(File srcImg, OutputStream output, Rectangle rect) {
        if (srcImg.exists()) {
            FileInputStream fis = null;
            ImageInputStream iis = null;
            try {
                fis = new FileInputStream(srcImg);
                // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
                String suffix = null;
                // 获取图片后缀
                if (srcImg.getName().indexOf(".") > -1) {
                    suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
                }// 类型和图片后缀全部小写，然后判断后缀是否合法
                if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase() + ",") < 0) {
                    return;
                }
                // 将FileInputStream 转换为ImageInputStream
                iis = ImageIO.createImageInputStream(fis);
                // 根据图片类型获取该种类型的ImageReader
                ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
                reader.setInput(iis, true);
                ImageReadParam param = reader.getDefaultReadParam();
                param.setSourceRegion(rect);
                BufferedImage bi = reader.read(0, param);
                ImageIO.write(bi, suffix, output);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) fis.close();
                    if (iis != null) iis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
        }
    }

    public static void cutImage(File srcImg, OutputStream output, int x, int y, int width, int height) {
        cutImage(srcImg, output, new Rectangle(x, y, width, height));
    }

    public static void cutImage(File srcImg, String destImgPath, Rectangle rect) {
        File destImg = new File(destImgPath);
        if (destImg.exists()) {
            String p = destImg.getPath();
            try {
                if (!destImg.isDirectory()) p = destImg.getParent();
                if (!p.endsWith(File.separator)) p = p + File.separator;
                cutImage(srcImg, new FileOutputStream(p + DEFAULT_CUT_PREVFIX + srcImg.getName()), rect);
                System.out.println(p + DEFAULT_CUT_PREVFIX + srcImg.getName());
            } catch (FileNotFoundException e) {
            }
        }
    }

    public void cutImage(File srcImg, String destImg, int x, int y, int width, int height) {
        cutImage(srcImg, destImg, new Rectangle(x, y, width, height));
    }

    public static void cutImage(String srcImg, String destImg, int x, int y, int width, int height) {
        cutImage(new File(srcImg), destImg, new Rectangle(x, y, width, height));
    }
}
